<template>
  <PageLayout full :page-style="pageStyle">
    <!--头部导航-->
    <template #header>
      <HeaderLayout show-back>
        <view>闹钟</view>
      </HeaderLayout>
    </template>
    <PageLayout safe-area="none">
      <!--头部导航-->
      <scroll-view class="scrollContBox" scroll-y>
        <!--无数据展示-->
        <view class="no-data" v-if="alarmList.length === 0">
          <image class="na-data-image" :src="netconfig.ASSETS_IMGURL + 'img_noclcok.png'"></image>
          <view class="no-data-text">您还没有闹钟哦</view>
        </view>
        <!--数据列表-->
        <view v-else>
          <view v-for="item in alarmList">
            <view class="cell">
              <!--删除按钮-->
              <view
                class="detele"
                @click="deleteAlarm(item)"
                :style="edit ? 'transform: translateX(144rpx);' : 'transform: translateX(0rpx);'"
              >
                <image src="/pages/appliance/static/HVN/ic_delete.png" class="delete-image"></image>
              </view>
              <view
                class="item"
                :class="{
                  'lose-clock': item.u == 1,
                }"
                :style="edit ? 'transform: translateX(136rpx);' : 'transform: translateX(0rpx);'"
              >
                <!--cell 左侧文字-->
                <view class="left-item">
                  <view class="title">{{ handleAlarmTitle(item.r) }}</view>
                  <view class="time">{{ item.t }}</view>
                  <view class="remark">{{ item.m }}</view>
                </view>
                <!--cell 右侧switch-->
                <switch color="var(--primary-color)" :checked="item.u === 0" @change="updateAlarm(item)"></switch>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
      <template #footer>
        <view class="add-alarm" @click="newAdd" v-if="alarmList.length === 0">添加闹钟</view>
        <view v-else class="add-alarm">
          <view class="edit" @click="editClick">{{ editText }}</view>
          <view class="line"></view>
          <view
            class="add"
            @click="newAdd"
            :class="{
              'lose-clock': edit,
            }"
            >添加闹钟</view
          >
        </view>
      </template>
    </PageLayout>
    <!--添加闹钟弹窗-->
    <Drawer v-model:show="addAlarm" v-if="addAlarm" title="添加闹钟" class="clockerDrawar" :bottom-offset="inputBottom">
      <!--时间选择器-->
      <view class="picker">
        <view class="left-picker">
          <picker-view indicator-class="clearBorder" class="picker-view">
            <picker-view-column>
              <view class="item" v-for="(item, index) in picker1" :key="index">{{ item }}</view>
            </picker-view-column>
          </picker-view>
        </view>
        <view class="right-picker">
          <picker-view
            @change="changeHour"
            indicator-class="clearBorder"
            class="hour-picker"
            :value="picker2"
            mask-style="background:transparent"
          >
            <picker-view-column>
              <view
                class="item right"
                :class="{ 'height-light-index': hightLightIndex == index }"
                v-for="(item, index) in picker2"
                :key="index"
                >{{ item }}</view
              >
            </picker-view-column>
          </picker-view>
          <view class="unit">:</view>
          <picker-view
            @change="changeMinute"
            indicator-class="clearBorder"
            class="minute-picker"
            mask-style="background:transparent"
          >
            <picker-view-column>
              <view
                class="item right"
                :class="{ 'height-light-index': hightLightIndexMinue == index }"
                v-for="(item, index) in picker3"
                :key="index"
                >{{ item }}</view
              >
            </picker-view-column>
          </picker-view>
        </view>
      </view>
      <!--启用时间-->
      <view class="set-text">启用时间</view>
      <view class="week-day">
        <view
          v-for="(item, index) in weekDays"
          :key="index"
          :style="selectDays.indexOf(index) != -1 ? selectedStyle : notSelectedStyle"
          @click="selectDay(index)"
          class="day"
          >{{ item }}</view
        >
      </view>
      <!--备注-->
      <view class="set-text">备注</view>
      <view class="remark-input">
        <view class="input-view">
          <input
            v-model="remarkName"
            class="input-set"
            :adjust-position="false"
            @keyboardheightchange="keyboardheightchange"
          />
          <image class="arrow" src="/pages/appliance/static/HVN/ic_toAll.png"></image>
        </view>
      </view>
      <!--保存按钮-->
      <view
        class="save-button"
        @click="save"
        :style="selectDays.length > 0 && remarkName.length > 0 ? itemOpenStyle : itemCloseStyle"
        :disabled="selectDays.length > 0 && remarkName.length > 0"
        >保存</view
      >
    </Drawer>
    <Modal v-model:visible="remarkCheck" :title="$t('APP.Common.Tips.Text')" :ok-text="$t('APP.Common.ISee.Text')">
      <text>{{ $t('HVN.Alarm.Add.Remark.Tip.Text') }}</text>
    </Modal>
  </PageLayout>
</template>
<script setup lang="ts">
import PageLayout from '@/layout/page/page.vue'
import HeaderLayout from '@/layout/page/header.vue'
import { useI18n } from 'vue-i18n'
import { onLoad } from '@dcloudio/uni-app'
import {
  getAlarmList,
  addAlarm as addAlarmRequest,
  deleteAlarm as deleteAlarmRequest,
  updateAlarm as updateAlarmRequest,
} from '@/api/hvn'
import type { AlarmModel } from '@/api/hvn'
import Drawer from '@/common/drawer.vue'
import Modal from '@/common/modal.vue'
import netconfig from '@/config/netconfig'
const pageStyle = {
  backgroundColor: '#FFFFFF',
}

const editText = ref('编辑')
const i18n = useI18n()
const alarmList = ref<AlarmModel[]>([])
const edit = ref(false)
const addAlarm = ref(false)
const picker1 = ref<string[]>([])
const picker2 = ref<string[]>([])
const picker3 = ref<string[]>([])
const weekDays = ['一', '二', '三', '四', '五', '六', '日']
const selectDays = ref<number[]>([])
const remarkName = ref('闹钟')
const refreshing = ref(false)
const remarkCheck = ref(false)
const hightLightIndex = ref(0)
const hightLightIndexMinue = ref(0)
let hour = '00'
let minute = '00'
let haId = ''

const selectedStyle = {
  background: '#408DF2',
  color: '#FFFFFF',
}
const notSelectedStyle = {
  background: '#E9E9ED',
  color: '#2D3746',
}

const itemOpenStyle = {
  opacity: 1.0,
}

const itemCloseStyle = {
  opacity: 0.4,
}
onLoad((options) => {
  haId = options?.haId
  getPicker1()
  getPicker2()
  getPicker3()
  getClockList(options?.haId)
})
const inputBottom = ref('')
function keyboardheightchange(e: WechatMiniprogram.InputKeyboardHeightChange) {
  let height = e.detail.height + 'rpx'
  inputBottom.value = height
}
function getPicker2() {
  let arr = []
  for (let i = 0; i < 24; i++) {
    arr.push(i < 10 ? '0' + i : i.toString())
  }
  picker2.value = arr
}

function getPicker1() {
  picker1.value = ['上午', '下午']
}

function getPicker3() {
  let arr = []
  for (let i = 0; i < 60; i++) {
    arr.push(i < 10 ? '0' + i : i.toString())
  }
  picker3.value = arr
}
function editName() {}
/**
 * 处理时间字符串
 * @param title
 */
function handleAlarmTitle(title: string) {
  if (title === '1,2,3,4,5') {
    return '每个工作日'
  } else if (title === '7,6') {
    return '周末'
  } else if (title === '7,1,2,3,4,5,6') {
    return '每天'
  } else {
    let day = ['1', '2', '3', '4', '5', '6', '7']
    let dayString = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    let weeks = title.split(',')
    let weekString = ''
    weeks.forEach((element) => {
      let index = day.indexOf(element)
      weekString = weekString + dayString[index]
    })
    return weekString
  }
}

/**
 *
 */
async function getClockList(haId: string) {
  let res = await getAlarmList(haId)
  if (alarmList.value.length > 0) {
    alarmList.value.splice(0, alarmList.value.length)
  }
  /**按照id排序 */
  res.data?.sort((a, b) => {
    return a.id - b.id
  })
  alarmList.value = res.data || []

  // 编辑状态时 清空编辑状态
  if (edit) {
    if (alarmList.value.length == 0) {
      edit.value = false
      editText.value = edit.value ? '完成' : '编辑'
    }
  }
}

function editClick() {
  edit.value = !edit.value
  editText.value = edit.value ? '完成' : '编辑'
}

/**
 * 选择哪天
 * @param index
 */
function selectDay(index: number) {
  let ind = selectDays.value.indexOf(index)
  if (selectDays.value.indexOf(index) != -1) {
    selectDays.value.splice(ind, 1)
  } else {
    selectDays.value.push(index)
  }
}

/**
 * 改变小时
 * @param e
 */
function changeHour(e: WechatMiniprogram.PickerViewChange) {
  hightLightIndex.value = e.detail.value[0]
  let _hour = picker2.value[e.detail.value[0]].replace(/\s+/g, '')
  hour = _hour
}

/**
 * 改变小时
 * @param e
 */
function changeMinute(e: WechatMiniprogram.PickerViewChange) {
  hightLightIndexMinue.value = e.detail.value[0]
  let _minute = picker3.value[e.detail.value[0]].replace(/\s+/g, '')
  minute = _minute
}

/**
 * 保存
 */
async function save() {
  // 先检查备注和日期是否为空
  if (selectDays.value.length <= 0 || remarkName.value.length <= 0) {
    return
  }
  // 检查备注内容是否符合要求
  let pattern = /^[\u4e00-\u9fa5a-zA-Z0-9]{1,8}$/
  if (!pattern.test(remarkName.value)) {
    remarkCheck.value = true
    return
  }

  let r = ''
  selectDays.value.forEach((element, index) => {
    r = r + (element + 1).toString()
    if (index != selectDays.value.length - 1) {
      r = r + ','
    }
  })
  addAlarm.value = false
  await addAlarmRequest(haId, remarkName.value, r, hour + ':' + minute, 0)
  setTimeout(() => {
    getClockList(haId)
  }, 500)
}

/**
 * 点击添加闹钟
 */
const alarmLimitCount = 10
function newAdd() {
  // 编辑时不允许添加闹钟
  if (edit.value) {
    return
  }
  if (alarmList.value.length >= alarmLimitCount) {
    uni.showToast({
      title: i18n.t('HVN.Alarm.Add.AlarmLimit.Tip.Text'),
      icon: 'none',
    })
    return
  }

  // 弹窗初始化
  hour = '00'
  minute = '00'
  hightLightIndex.value = 0
  hightLightIndexMinue.value = 0
  // 弹窗标识符
  addAlarm.value = true
  if (selectDays.value.length > 0) {
    selectDays.value.splice(0, selectDays.value.length)
    remarkName.value = '闹钟'
  }
}

/**
 * 删除某条闹钟
 * @param model
 */
async function deleteAlarm(model: AlarmModel) {
  let { m, r, t, u, id } = model
  await deleteAlarmRequest(haId, { m, r, t, u, id })
  setTimeout(() => {
    getClockList(haId)
  }, 500)
}
/**
 * 更新闹钟信息
 */
async function updateAlarm(model: AlarmModel) {
  let { m, r, t, id } = model
  let u = 1
  if (model.u === 1) {
    u = 0
  }
  await updateAlarmRequest(haId, { m, r, t, u, id })
  setTimeout(() => {
    getClockList(haId)
  }, 500)
}
</script>

<style lang="less">
.clockerDrawar {
  .drawer-inner {
    height: calc(100vh - 362rpx) !important;
    .drawer-body {
      position: relative;
    }
  }
}
.scrollContBox {
  background-color: white;
  height: 100%;
  margin-top: 48rpx;
}
.no-data {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  // justify-content: center;
  margin-top: 120rpx;
  align-items: center;
  image {
    height: 428rpx;
    width: 550rpx;
  }
  .no-data-text {
    margin-top: 24rpx;
    font-family: 'PingFang SC';
    font-style: normal;
    font-weight: 400;
    font-size: 32rpx;
    color: #b4b9c3;
  }
}
.cell {
  width: 100%;
  height: 216rpx;
  margin-bottom: 24rpx;
  position: relative;
  .detele {
    position: absolute;
    height: 100%;
    width: 144rpx;
    display: flex;
    justify-content: space-around;
    align-items: center;
    left: -144rpx;
    image {
      width: 48rpx;
      height: 48rpx;
    }
  }
  .item {
    background: #f4f4f6;
    margin-left: 24rpx;
    margin-right: 24rpx;
    height: 100%;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;

    .left-item {
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      align-items: flex-start;
      margin-left: 32rpx;
      .title {
        font-family: 'Inter';
        font-style: normal;
        font-weight: 500;
        font-size: 28rpx;
        /* Primary/Petrol */
        color: #2d3746;
      }
      .time {
        font-family: 'Inter';
        font-style: normal;
        font-weight: 500;
        font-size: 56rpx;
        color: #408df2;
      }
      .remark {
        font-family: 'Inter';
        font-style: normal;
        font-weight: 500;
        font-size: 28rpx;
        /* Primary/Petrol */
        color: #2d3746;
      }
    }
    switch {
      margin-right: 32rpx;
      width: 76rpx;
      height: 40rpx;
    }
  }
}
.lose-clock {
  opacity: 0.4;
}
.add-alarm {
  background: #2d3746;
  color: #ffffff;
  height: 88rpx;
  margin-left: 32rpx;
  margin-right: 32rpx;
  margin-bottom: 64rpx;
  font-family: 'PingFang SC';
  font-style: normal;
  font-weight: 600;
  font-size: 32rpx;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  line-height: 88rpx;
  text-align: center;
  .edit {
    width: 240rpx;
    text-align: center;
  }
  .line {
    width: 4rpx;
    height: 44rpx;
    background: #ffffff;
  }
  .add {
    text-align: center;
    flex: 1;
  }
}

.picker {
  margin-left: 100rpx;
  margin-right: 150rpx;
  height: 320rpx;
  margin-top: 0rpx;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;

  .left-picker {
    display: none;
    height: 208rpx;
    margin-top: 56rpx;
    margin-right: 56rpx;
    width: 80rpx;
    .picker-view {
      width: 80rpx;
      height: 100%;
    }
  }
  .right-picker {
    height: 208rpx;
    flex: 1;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    margin-top: 56rpx;
    margin-right: 56rpx;
    .hour-picker {
      height: 100%;
      width: 200rpx;
      /deep/ .item {
        color: rgba(45, 55, 70, 0.8);
        font-weight: 400;
      }
    }
    .minute-picker {
      height: 100%;
      width: 200rpx;
      /deep/ .item {
        color: rgba(45, 55, 70, 0.8);
        font-weight: 400;
      }
    }
    /deep/ .height-light-index {
      color: #408df2 !important;
      font-weight: 600;
    }
    .unit {
      width: 16rpx;
      height: 80rpx;
      font-family: 'PingFang SC';
      font-style: normal;
      font-weight: 600;
      font-size: 56rpx;
      /* Primary/Blue/Medium */
      color: #408df2;
    }
  }
}
.item {
  height: 100%;
  text-align: center;
}
/deep/ .clearBorder {
  color: var(--primary-blue-medium, #408df2);
}

.clearBorder::after {
  border: none;
}

.clearBorder::before {
  border: none;
}
.right {
  font-family: 'PingFang SC';
  font-style: normal;
  font-weight: 600;
  font-size: 56rpx;
  color: #408df2;
}
.set-text {
  font-family: 'PingFang SC';
  font-style: normal;
  font-weight: 400;
  font-size: 32rpx;
  color: #000000;
  margin-left: 32rpx;
}

.week-day {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
  margin: 32rpx;
  .day {
    width: 80rpx;
    height: 80rpx;
    border-radius: 40rpx;
    background: #e9e9ed;
    line-height: 80rpx;
    text-align: center;
  }
}
.remark-input {
  padding: 24rpx 32rpx;
  .input-view {
    width: 100%;
    position: relative;
    &::after {
      content: '';
      display: block;
      position: absolute;
      bottom: -24rpx;
      left: 0;
      width: 100%;
      height: 2rpx;
      background-color: #e9e9ed;
    }
    .input-set {
      display: flex;
      align-items: center;
      font-weight: 500;
      height: 40rpx;
      font-size: 40rpx;
      color: #408df2;
      box-sizing: border-box;
      overflow: hidden;
    }
    .arrow {
      width: 16rpx;
      height: 32rpx;
      position: absolute;
      right: 0;
      bottom: calc(50% - 16rpx);
    }
  }
  .line {
    width: 100%;
    height: 2rpx;
    background: #e9e9ed;
    margin-top: 24rpx;
  }
}
.save-button {
  position: absolute;
  bottom: 2%;
  // margin-top: 36%;
  background: #2d3746;
  font-family: 'PingFang SC';
  font-style: normal;
  font-weight: 600;
  font-size: 32rpx;
  text-align: center;
  height: 88rpx;
  line-height: 88rpx;
  color: #ffffff;
  width: 90%;
}

.select {
  background: #408df2;
  color: #ffffff;
  width: 80rpx;
  height: 80rpx;
  border-radius: 40rpx;
  line-height: 80rpx;
  text-align: center;
}
</style>
